package com.hrbu.springboot04.advice;

import com.hrbu.springboot04.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 配置异常处理类
 * @Author: tanyajun
 * @CreateTime: 2021/4/8
 * @Blog: https://tanyajun.top
 */
@ControllerAdvice
public class MyControllerAdvice {
    @ExceptionHandler(MyException.class)
    public String myException(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取自定义异常
        MyException e = (MyException) request.getAttribute("org.springframework.boot.web.servlet.error.DefaultErrorAttributes.ERROR");
        request.setAttribute("status", e.getCode());
        request.setAttribute("message", e.getMessage());
        String path="error/";
        switch (e.getCode()){
            case 404:
                path+="404";
                break;
            case 500:
                path+="500";
                break;
            default:
                path+="xxx";
                break;
        }
        return path;
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}